<template>
  <div class="app-container">
    <div class="page-header">
      <el-button @click="handleBack">返回列表</el-button>
      <h2>{{ route.params.id ? '编辑试卷' : '新增试卷' }}试卷</h2>
      <el-button type="primary" @click="handleSave">保存试卷</el-button>
    </div>

    <!-- 试卷基本信息表单 -->
    <el-card class="basic-info-card">
      <el-form :model="formData" ref="formRef" label-width="100px" class="basic-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="试卷名称" prop="name" :rules="[{ required: true, message: '请输入试卷名称', trigger: 'blur' }]">
              <el-input v-model="formData.name" placeholder="请输入试卷名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="省-市" prop="area" :rules="[{ required: true, message: '请选择地区', trigger: 'change' }]">
              <el-cascader v-model="formData.area" :options="areaOptions" placeholder="请选择地区"
                :props="{ expandTrigger: 'hover' }" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年级" prop="grade" :rules="[{ required: true, message: '请选择年级', trigger: 'change' }]">
              <el-select v-model="formData.grade" placeholder="请选择年级">
                <el-option v-for="grade in gradeOptions" :key="grade" :label="grade" :value="grade" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="科目" prop="subject" :rules="[{ required: true, message: '请选择科目', trigger: 'change' }]">
              <el-select v-model="formData.subject" placeholder="请选择科目">
                <el-option v-for="subject in subjectOptions" :key="subject.value" :label="subject.label"
                  :value="subject.value" />
              </el-select>
            </el-form-item>

            <!-- 考试时间 默认1小时 -->
             <el-form-item label="考试时间" prop="examTime" :rules="[{ required: true, message: '请选择考试时间', trigger: 'change' }]">
              <el-select v-model="formData.examTime" placeholder="请选择考试时间">
                <el-option  label="10分钟" :value="10" />
                <el-option  label="20分钟" :value="20" />
                <el-option  label="30分钟" :value="30" />
                <el-option  label="40分钟" :value="40" />
                <el-option  label="50分钟" :value="50" />
                <el-option  label="60分钟" :value="60" />
                <el-option  label="90分钟" :value="90" />
                <el-option  label="120分钟" :value="120" />
                <el-option  label="150分钟" :value="150" />
                <el-option  label="180分钟" :value="180" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 试题部分 -->
    <el-card class="questions-card">
      <div class="questions-header">
        <h3>试题内容</h3>
      </div>

      <!-- 试题类型标签页 -->
      <el-tabs v-model="activeTab" type="border-card" class="questions-tabs">
        <!-- 选择题区域 -->
        <el-tab-pane label="选择题" name="choice">
          <div class="question-type-container">
            <div class="add-question">
              <el-button type="primary" icon="Plus" @click="addQuestion('choice')">
                添加选择题
              </el-button>
            </div>

            <div v-for="(question, index) in questions.choice" :key="index" class="question-item">
              <div class="question-header">
                <span class="question-number">第{{ index + 1 }}题</span>
                <el-button type="text" icon="Delete" class="delete-btn" @click="removeQuestion('choice', index)">
                  删除
                </el-button>
              </div>

              <el-row :gutter="20" class="question-content">
                <el-col :span="18">
                  <el-form-item label="题目" :prop="`choice.${index}.content`"
                    :rules="[{ required: true, message: '请选择题目', trigger: 'change' }]">
                    <el-select v-model="question.content" placeholder="从题库选择题目"
                      @change="handleSelectChange(question, 'choice')">
                      <el-option v-for="item in questionBank.choice" :key="item.id" :label="item.name" :value="item.id">
                        {{ item.name }}
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="分值" :prop="`choice.${index}.score`"
                    :rules="[{ required: true, message: '请输入分值', trigger: 'blur' }]">
                    <el-input-number v-model="question.score" :min="1" :max="100" :step="1" controls-position="right"
                      placeholder="分值" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row v-if="question.content">
                <div class="question-name">{{ question.info.name }}</div>
                <div class="question-name" v-if="question.info.description">{{ question.description }}</div>
                <div class="question-content">
                  <el-checkbox-group v-if="question.info.isMultiple">
                    <div v-for="(option, index) in question.info.options" :key="index" class="option-item">
                      <div class="option-selector">
                        <el-checkbox :label="option.label" :key="option.value" :value="option.value" />
                      </div>

                    </div>
                  </el-checkbox-group>
                  <el-radio-group v-if="!question.info.isMultiple">
                    <div v-for="(option, index) in question.info.options" :key="index" class="option-item">
                      <div class="option-selector">
                        <el-radio :label="option.label" :key="option.value" :value="option.value" />
                      </div>


                    </div>
                  </el-radio-group>

                </div>
              </el-row>
            </div>

            <div v-if="questions.choice.length === 0" class="empty-state">
              <el-empty description="暂无选择题，请添加" />
            </div>
          </div>
        </el-tab-pane>

        <!-- 填空题区域 -->
        <el-tab-pane label="填空题" name="fill">
          <div class="question-type-container">
            <div class="add-question">
              <el-button type="primary" icon="Plus" @click="addQuestion('fill')">
                添加填空题
              </el-button>
            </div>

            <div v-for="(question, index) in questions.fill" :key="index" class="question-item">
              <div class="question-header">
                <span class="question-number">第{{ index + 1 }}题</span>
                <el-button type="text" icon="Delete" class="delete-btn" @click="removeQuestion('fill', index)">
                  删除
                </el-button>
              </div>

              <el-row :gutter="20" class="question-content">
                <el-col :span="18">
                  <el-form-item label="题目" :prop="`fill.${index}.content`"
                    :rules="[{ required: true, message: '请选择题目', trigger: 'change' }]">
                    <el-select v-model="question.content" @change="handleSelectChange(question, 'fill')"
                      placeholder="从题库选择题目">
                      <el-option v-for="item in questionBank.fill" :key="item.id" :label="item.name" :value="item.id">
                        {{ item.name }}
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="分值" :prop="`fill.${index}.score`"
                    :rules="[{ required: true, message: '请输入分值', trigger: 'blur' }]">
                    <el-input-number v-model="question.score" :min="1" :max="100" :step="1" controls-position="right"
                      placeholder="分值" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row v-if="question.content">
                <div class="question-name">{{ question.info.name }}</div>
                <div class="question-name" v-if="question.info.description">{{ question.description }}</div>
              </el-row>
            </div>

            <div v-if="questions.fill.length === 0" class="empty-state">
              <el-empty description="暂无填空题，请添加" />
            </div>
          </div>
        </el-tab-pane>

        <!-- 解答题区域 -->
        <el-tab-pane label="解答题" name="answer">
          <div class="question-type-container">
            <div class="add-question">
              <el-button type="primary" icon="Plus" @click="addQuestion('answer')">
                添加解答题
              </el-button>
            </div>

            <div v-for="(question, index) in questions.answer" :key="index" class="question-item">
              <div class="question-header">
                <span class="question-number">第{{ index + 1 }}题</span>
                <el-button type="text" icon="Delete" class="delete-btn" @click="removeQuestion('answer', index)">
                  删除
                </el-button>
              </div>

              <el-row :gutter="20" class="question-content">
                <el-col :span="18">
                  <el-form-item label="题目" :prop="`answer.${index}.content`"
                    :rules="[{ required: true, message: '请选择题目', trigger: 'change' }]">
                    <el-select v-model="question.content" @change="handleSelectChange(question, 'answer')"
                      placeholder="从题库选择题目">
                      <el-option v-for="item in questionBank.answer" :key="item.id" :label="item.name" :value="item.id">
                        {{ item.name }}
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="分值" :prop="`answer.${index}.score`"
                    :rules="[{ required: true, message: '请输入分值', trigger: 'blur' }]">
                    <el-input-number v-model="question.score" :min="1" :max="100" :step="1" controls-position="right"
                      placeholder="分值" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row v-if="question.content">
                <div class="question-name">{{ question.info.name }}</div>
                <div class="question-name" v-if="question.info.description">{{ question.description }}</div>
              </el-row>
            </div>

            <div v-if="questions.answer.length === 0" class="empty-state">
              <el-empty description="暂无解答题，请添加" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElForm } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';

defineOptions({
  name: 'testPaperAdd', // 新增试卷组件
})
const router = useRouter();
const route = useRoute();

const formRef = ref(null);
const activeTab = ref('choice');

// 表单数据
const formData = reactive({
  name: '',
  area: ['安徽', '合肥'],
  grade: '初一',
  subject: '数学',
  examTime: 60, // 考试时间，单位分钟
});

// 题目数据
const questions = reactive({
  choice: [], // 选择题
  fill: [],   // 填空题
  answer: []  // 解答题
});

// 地区选项
const areaOptions = ref([{
  value: '安徽',
  label: '安徽',
  children: [{
    value: '合肥',
    label: '合肥'
  }]
}]);

// 年级选项
const gradeOptions = ['初一', '初二', '初三', '高一'];

// 科目选项
const subjectOptions = [
  { label: '数学', value: '数学' },
  { label: '英语', value: '英语' }
];

// 模拟题库数据
const questionBank = reactive({
  choice: [
    {
      id: 1,
      name: 'choice 111', // 题目题干
      description: '', // 题目描述
      type: 'choice',
      options: [
        { label: '选项A', value: 'A' },
        { label: '选项B', value: 'B' },
        { label: '选项C', value: 'C' },
        { label: '选项D', value: 'D' }
      ],
      isMultiple: true,
      singleAnswer: null,   // 单选答案
      multipleAnswers: [],   // 多选答案（改为数组存储）
      referenceAnswer: 'B',   // 参考答案
      answerInfo: '',        // 答案解析
      knowledgePoints: []
    },

    {
      id: 2,
      name: 'choice 2', // 题目题干
      description: '', // 题目描述
      type: 'choice',
      options: [
        { label: '选项A', value: 'A' },
        { label: '选项B', value: 'B' },
        { label: '选项C', value: 'C' },
        { label: '选项D', value: 'D' }
      ],
      isMultiple: false,
      singleAnswer: null,   // 单选答案
      multipleAnswers: [],   // 多选答案（改为数组存储）
      referenceAnswer: 'A',   // 参考答案
      answerInfo: '',        // 答案解析
      knowledgePoints: []
    },

    {
      id: 3,
      name: 'choice 3', // 题目题干
      description: '', // 题目描述
      type: 'choice',
      options: [
        { label: '选项A', value: 'A' },
        { label: '选项B', value: 'B' },
        { label: '选项C', value: 'C' },
        { label: '选项D', value: 'D' }
      ],
      isMultiple: false,
      singleAnswer: null,   // 单选答案
      multipleAnswers: [],   // 多选答案（改为数组存储）
      referenceAnswer: 'C',   // 参考答案
      answerInfo: '',        // 答案解析
      knowledgePoints: []
    },

  ],
  fill: [
    {
      id: 5, name: 'fill 1', // 题目题干
      description: '', // 题目描述
      type: 'fill',
      options: [],
      isMultiple: false,
      singleAnswer: null,   // 单选答案
      multipleAnswers: [],   // 多选答案（改为数组存储）
      referenceAnswer: 'dddd',   // 参考答案
      answerInfo: 'jiex=cja i 解答题目',        // 答案解析
      knowledgePoints: []
    },
  ],
  answer: [
    {
      id: 7,
      name: 'answer1', // 题目题干
      description: '', // 题目描述
      type: 'answer',
      options: [],
      isMultiple: false,
      singleAnswer: null,   // 单选答案
      multipleAnswers: [],   // 多选答案（改为数组存储）
      referenceAnswer: 'dddd',   // 参考答案
      answerInfo: 'jiex=cja i 解答题目',        // 答案解析
      knowledgePoints: []
    },

    {
      id: 8,
      name: 'answer2', // 题目题干
      description: '', // 题目描述
      type: 'answer',
      options: [],
      isMultiple: false,
      singleAnswer: null,   // 单选答案
      multipleAnswers: [],   // 多选答案（改为数组存储）
      referenceAnswer: 'dddd',   // 参考答案
      answerInfo: 'jiex=cja i 解答题目',        // 答案解析
      knowledgePoints: []
    },

  ]
});


const questionTemplate = {
  name: '',   // 题目题干
  description: '', // 题目描述
  type: 'choice',
  options: [
    { label: '选项A', value: 'A' },
    { label: '选项B', value: 'B' },
    { label: '选项C', value: 'C' },
    { label: '选项D', value: 'D' }
  ],
  isMultiple: false,
  singleAnswer: null,   // 单选答案
  multipleAnswers: [],   // 多选答案（改为数组存储）
  referenceAnswer: '',   // 参考答案
  answerInfo: '',        // 答案解析
  knowledgePoints: []  // 新增：关联知识点数组
};
// 添加题目
const addQuestion = (type) => {


  questions[type].push({
    id: Date.now(),
    content: '', // 关联的是题目的id 
    score: 10,
    info: { ...questionTemplate }, // 题目模板， 在选中的时候用实际题目去覆盖
  });

  // 自动切换到当前标签页
  activeTab.value = type;
};

// 删除题目
const removeQuestion = (type, index) => {
  ElMessageBox.confirm('确定要删除这道题吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    questions[type].splice(index, 1);
    ElMessage.success('删除成功');
  }).catch(() => { });
};

// 选中题目
function handleSelectChange(question, type) {
  // 从题库中找到选中的题目
  const selectedQuestion = questionBank[type].find(item => item.id === question.content);
  if (selectedQuestion) {
    // 用选中的题目覆盖模板
    question.info = { ...selectedQuestion };
  }
}

// 表单验证
const validateForm = async () => {
  // 先验证基本信息
  const basicValid = await formRef.value.validate();
  if (!basicValid) return false;

  // 验证题目是否添加
  if (questions.choice.length === 0 && questions.fill.length === 0 && questions.answer.length === 0) {
    ElMessage.error('请至少添加一道题目');
    return false;
  }

  // 验证每题都已选择内容和分值
  for (const type of ['choice', 'fill', 'answer']) {
    for (let i = 0; i < questions[type].length; i++) {
      const question = questions[type][i];
      if (!question.name) {
        ElMessage.error(`请选择${getTypeName(type)}第${i + 1}题的题目内容`);
        activeTab.value = type;
        return false;
      }
      if (!question.score || question.score < 1 || question.score > 100) {
        ElMessage.error(`请正确设置${getTypeName(type)}第${i + 1}题的分值`);
        activeTab.value = type;
        return false;
      }
    }
  }

  return true;
};

// 获取题型名称
const getTypeName = (type) => {
  switch (type) {
    case 'choice': return '选择题';
    case 'fill': return '填空题';
    case 'answer': return '解答题';
    default: return '';
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!await validateForm()) return;

  // 构建提交数据
  const submitData = {
    ...formData,
    questions: {
      choice: questions.choice,
      fill: questions.fill,
      answer: questions.answer
    }
  };

  // 模拟提交
  console.log('提交试卷数据:', submitData);

  ElMessageBox.success('试卷创建成功！');
  router.push('/testPaper');
};

// 保存草稿
const handleSave = async () => {
  if (!formData.name) {
    ElMessage.error('请输入试卷名称');
    return;
  }

  // 模拟保存草稿
  ElMessage.success('草稿保存成功');
};

// 返回列表
const handleBack = () => {
  router.push('/testPapers/index');
};

// 获取编辑好的数据 -- 填入 questions formData 
async function getTestPaperById(id) {
  
}

// 页面加载时初始化
onMounted(() => {
  if (route.query.id) {
    // 编辑模式
    getTestPaperById(route.query.id);
  }
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  gap: 20px;
}

.page-header h2 {
  margin: O;
  font-size: 24px;
}

.basic-info-card {
  margin-bottom: 20px;
}

.basic-form {
  padding: 10px 0;
}

.questions-card {
  margin-bottom: 30px;
}

.questions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.questions-tabs {
  margin-top: 10px;
}

.question-type-container {
  padding: 10px;
}

.add-question {
  margin-bottom: 20px;
}

.question-item {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  position: relative;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.question-number {
  font-weight: bold;
  color: #1f2937;
}

.delete-btn {
  color: #ef4444;
}

.question-content {
  margin-top: 10px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.submit-area {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style>